﻿using System;
using System.Linq;
using Ease.EaseMission.Editor.Node;
using Ease.EaseMission.Runtime;
using Ease.EaseNode.Editor.NodeView;
using UnityEditor;
using UnityEditor.Experimental.GraphView;
using UnityEngine;
using UnityEngine.UIElements;

namespace Ease.EaseMission.Editor.View
{
    public class MsChartView : BaseEaseChartView
    {
        public Action<BaseEaseNode> OnNodeEditor;

        public new class UxmlFactory : UxmlFactory<MsChartView, UxmlTraits>
        {
        }

        public MsChartView() : base()
        {
            var styleSheet = AssetDatabase.LoadAssetAtPath<StyleSheet>("Assets/Ease/EaseMission/Editor/MissionEW.uss");
            styleSheets.Add(styleSheet);
        }

        public void SetMenu<T>() where T : BaseSearchMenuWindowProvider
        {
            //新建搜索菜单
            T menuWindowProvider = ScriptableObject.CreateInstance<T>();
            menuWindowProvider.OnSelectEntryHandler += OnMenuSelectEntry;
            nodeCreationRequest = null;
            nodeCreationRequest += context => { SearchWindow.Open(new SearchWindowContext(context.screenMousePosition), menuWindowProvider); };
        }

        protected override void SetInitParam(InitParam initParam)
        {
            if (initParam is MissionInitParam param)
            {
                if (param.nodeType == typeof(MissionStage))
                {
                    nodes.FirstOrDefault(x =>
                    {
                        var temp = x as MissionStageNode;
                        if (temp != null && temp.State.Data is MissionStage b)
                        {
                            return b != null && b.Id == param.selectID;
                        }

                        return false;
                    })?.Select(this, false);
                }
                else if (param.nodeType == typeof(MissionStep))
                {
                    nodes.FirstOrDefault(x =>
                    {
                        var temp = x as MissionStepNode;
                        if (temp != null && temp.State.Data is MissionStep b)
                        {
                            return b != null && b.Id == param.selectID;
                        }

                        return false;
                    })?.Select(this, false);
                }
                else
                {
                    base.SetInitParam(initParam);
                }
            }
            else
            {
                base.SetInitParam(initParam);
            }
        }

        protected override void OnCreateNewNode(BaseEaseNode newNode)
        {
            if (newNode is IOnNodeEditor editor)
            {
                editor.OnNodeEditor += OnNodeEditor;
            }
        }
    }
}